#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
  ui->setupUi(this);

  setWindowTitle("TCP客户端(方式二)");
  // 2
  m_thread.start();

  // 3，调用moveToThread将对象移动至线程中
  m_taskWorker.moveToThread(&m_thread);
  qDebug() << "QThread对象的地址" << &m_thread;

  // 连接信号槽
  connect(this, &Widget::init, &m_taskWorker, &TaskWorker::init,Qt::QueuedConnection);
  connect(this, &Widget::onSend, &m_taskWorker, &TaskWorker::onSend,Qt::QueuedConnection);
  connect(this, &Widget::onClose, &m_taskWorker, &TaskWorker::onClose,Qt::QueuedConnection);

  connect(&m_taskWorker, &TaskWorker::showMessage, this, &Widget::showMessage,Qt::QueuedConnection);
}

Widget::~Widget() {
  // 关闭套接字
  emit onClose();
  // quit退出线程的消息循环
  m_thread.quit();
  // 等待线程结束
  m_thread.wait();
  qDebug() << "线程退出了！";

  delete ui;
}


void Widget::showMessage(const QString &info ) {
  ui->messageShoxEdit->appendPlainText(info);

}

void Widget::on_btnSend_clicked() {
  if(!m_start){
    QString ip = ui->lineEditIP->text();
    uint port = ui->lineEditPort->text().toUInt();
    emit init(ip ,port);
    m_start = true;
    QThread::sleep(1); //等待线程启动
  }

  QString msg = ui->messageEdit->text();
  emit onSend(msg);

}
